<script setup lang="ts">
import {nextTick, reactive, ref} from 'vue'
import {useRouter, useRoute} from 'vue-router'
import HeaderVue from '@/components/Header.vue'
import {ServerUtils} from '@/serverUtils'
import {Server} from '@/stores/ajax';
import {RouterLink, RouterView} from 'vue-router'
import {format as timeFormat} from 'silly-datetime'
import {
    ArrowLeft, Plus
} from '@element-plus/icons-vue'
import {ElMessage, type UploadRawFile} from 'element-plus'
import {Delta, QuillEditor} from '@vueup/vue-quill'
import MyQuill from '@/components/quillComponent.vue'
import type {FormInstance, FormRules, UploadProps} from 'element-plus'
import workList from '@/components/bbs/postList3.vue'
let event = $ref<any>()
const router = useRouter()
const route = useRoute()
const sid = Number(route.params.sid)
const refresh = async () => {
    await ServerUtils.getSubarea(sid).then(subarea => {
        const configEvents = (window as any).cauis.events as any[]
        let configEvent = configEvents.find(e => e.subarea_id == sid)
        if (!subarea || !configEvent) return
        event = configEvent
        if (event.title == '$DEFAULT') {
            event.title = subarea.name
        }
        if (event.info == '$DEFAULT') {
            event.info = subarea.description ?? ''
        }
        if (event.page == '$DEFAULT') {
            event.page = 'e1'
        }
        event.subarea = subarea
    })
}
const works = ref<any[]>([])
refresh()
const tab = ref(1)
const handleUploadWork = () => {
    tab.value = 2
    nextTick(() => {
    })
}

let editor = $ref<any>()
let content = $ref<Delta>(new Delta())
let maxPostWordsLength = 9000
const handlePost = async () => {
    await ruleFormRef.validate(async (valid, fields) => {
        if (valid) {
            await ServerUtils.post(editor, event.subarea.id, ruleForm.name, 5, maxPostWordsLength, imageUrl.value).then((res: any) => {
                console.log(res)
                router.push({path: `/bbs/forums/topic/${res.topicid}`})
            })
        } else {
            console.log("error submit!", fields);
        }
    });

}
const ruleFormRef = $ref<FormInstance>()
const workCallback = async(page: number, posts_per_page: number) => {
    return ServerUtils.getTopics(["vote"],2, event.subarea_id, 'create_time', page, posts_per_page)
}
const ruleForm = reactive({
    name: '',
})
const rules = reactive<FormRules>({
    name: [
        {required: true, message: '必须输入标题', trigger: 'blur'},
        {min: 2, max: 30, message: '标题应该在2-30字之间', trigger: 'blur'},
    ],
})

const imageUrl = ref('')

const handleUploadImage: UploadProps['onChange'] = async (file, files) => {
    const rawFile = file.raw as UploadRawFile
    console.log(rawFile)
    if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片应该小于5MB!')
        files.pop()
        return
    }
    if (files.length > 1)
        files.shift()
    await ServerUtils.uploadImage(rawFile).then(res => {
        console.log(res)
        imageUrl.value = res ?? ''
    })
}
const handleUploadFileRemove: UploadProps['onRemove'] = async (file, files) => {
    imageUrl.value = ''
}
</script>

<template>
    <header>
        <HeaderVue />
    </header>
    <div class="activity">

        <div class="activity-intro fhs card-block"
            v-if='event'>

            <div class="pic"
                :style='`background-image: url("${event.image2}");`'>
            </div>
            <div class="besize-pic">
                <div class="title" v-text='event.title' />
                <div class="info">
                    活动介绍：{{ event.info}}<br>
                    活动时间：{{
                            timeFormat(event.start_time,
                                "YYYY年MM月DD日")
                    }}
                    -
                    {{ timeFormat(event.end_time,
                            "YYYY年MM月DD日")
                    }}<br>
                    <div class='other-info'
                        v-dompurify-html='event.other_info' />

                </div>
                <el-button class="b1" color="#6666cc"
                    @click="handleUploadWork">
                    上传作品
                </el-button>
            </div>

        </div>
        <div v-if='tab == 1'>
            <div class="label1">
                作品一览
            </div>
            <workList v-if='event' :post-callback="workCallback" />
                    </div>
        <div v-if="tab == 2">
            <div class="top-line fhs">
                <el-button :icon="ArrowLeft" class="b1"
                    style="" color="#fff0" @click="tab = 1">
                    查看作品
                </el-button>
            </div>
            <div class="label2">
                作品上传
            </div>
            <div class="card-block upload-block">
                <el-form ref="ruleFormRef" :model="ruleForm"
                    :rules="rules" label-width="120px"
                    label-position="top">
                    <el-form-item prop="name">
                        <template #label>
                            <label
                                class="label-topic-title">作品标题</label>
                        </template>
                        <el-input v-model="ruleForm.name"
                            placeholder="输入标题" clearable />
                    </el-form-item>
                    <label
                        class="label-topic-title">作品内容</label>

                    <div class="text-area">
                        <MyQuill theme="snow"
                            content-type="delta"
                            class="post-quill"
                            placeholder="输入文字"
                            :content="content"
                            @ready="(e) => {editor = e}"
                            :max-words-length="maxPostWordsLength" />
                    </div>
                    <label
                        class="label-topic-title">缩略图</label>
                    <el-upload class="uploader"
                        :auto-upload='false'
                        :on-change="handleUploadImage"
                        accept='image/png, image/jpeg'
                        :on-remove="handleUploadFileRemove"
                        :limit="2">
                        <img v-if="imageUrl"
                            :src="Server.fileBaseURL + imageUrl"
                            class="avatar" />
                        <el-icon v-else
                            class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                    <el-button class="b-post"
                        @click="handlePost" color="#6666cc">
                        发布
                    </el-button>
                </el-form>
            </div>
        </div>

    </div>
</template>

<style scoped lang="scss">
$core-width : 1080px;

.activity {
    width: $core-width;
    margin: 0 auto;

    .card-block {
        border-radius: 8px;
        box-shadow: 0 0 0 1px hsl(0deg 0% 100% / 30%) inset, 0 0.5em 1em rgb(0 0 0 / 2%);
        background-color: white;
        margin-top: 20px;
        padding: 36px 36px;
    }

    .activity-intro {
        /* width: 100%; */
        height: 260px;

        .pic {
            /* height: 100px; */
            min-width: 500px;
            max-width: 500px;
            /* height: 250px; */
            background-size: cover;
            border-radius: 0;
        }

        .besize-pic {
            margin-left: 36px;
        }

        .title {
            font-size: 32px;
        }

        .info {
            height: 178px;
            line-height: 24px;
        }

        .b1 {
            font-size: 16px;
            letter-spacing: 10px;
            border-radius: 4px;
            padding: 20px 36px;
        }

        .b1.b1 {
            text-indent: -10px;
            direction: rtl;
        }

    }

    .label1 {
        font-weight: bold;
        font-size: 24px;
        margin: 34px 0 20px;

    }


    .label2 {
        font-weight: bold;
        font-size: 24px;
        margin: 14px 0 20px;

    }



    .top-line {
        margin: 10px;
        align-items: center;

        .b1 {
            border-width: 0;
            justify-content: start;
            color: #999;
            padding: 0;
            margin-right: 20px;
        }

        .b1:hover {
            color: #666;
            background-color: #fff0;
        }

        .b1:active {
            color: #ccc;
            background-color: #fff0;
        }

        .bc:hover {
            color: #444;
        }

    }

    .upload-block {
        .label-topic-title {
            font-size: 20px;
            font-weight: bold;
            color: #333333;
            text-align: left;
        }

        .text-area {
            padding-top: 8px;
            height: 500px;
        }


        .b-post {
            margin: 10px 0 30px;
            font-size: 16px;
            min-width: 100px;
            letter-spacing: 10px;
        }

        .b-post.b-post {
            text-indent: -10px;
            direction: rtl;
        }


    }
}
</style>
<style lang="scss">
.uploader {
    margin: 10px 0;
    max-width: 350px;

    .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    img {
        max-width: 100%;
    }
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>

